using System;
using System.Data;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Editor;
using mojoPortal.Web.Framework;
using mojoPortal.Business;
using eStore.Business;
using eStore.Helpers;
using Resources;

namespace eStore.UI
{
    public partial class AdminStoreSettingsPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Store store;
        private Module module;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.SslIsAvailable()) SiteUtils.ForceSsl();

            LoadSettings();

            if ((store == null) || (!UserCanEditModule(moduleId)))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            PopulateLabels();

            if (Page.IsPostBack) return;
            BindDropdownLists();
            PopulateControls();
        }

        private void PopulateControls()
        {
            //Store store = new Store(siteSettings.SiteGuid, moduleId);
            //Module module = new Module(moduleId);
            if (store == null) return;
            if (module == null) return;
            if (module.ModuleId == -1) return;

            txtName.Text = module.ModuleTitle;
            edDescription.Text = store.Description;
            txtOwnerName.Text = store.OwnerName;
            txtOwnerEmail.Text = store.OwnerEmail;

            if (store.CountryGuid != Guid.Empty)
            {
                ListItem listItem = ddCountryGuid.Items.FindByValue(store.CountryGuid.ToString());
                if (listItem != null)
                {
                    ddCountryGuid.ClearSelection();
                    listItem.Selected = true;
                    BindZoneList();
                }
            }

            txtAddress.Text = store.Address;
            txtCity.Text = store.City;
            if (store.ZoneGuid != Guid.Empty)
            {
                ListItem listItem = ddZoneGuid.Items.FindByValue(store.ZoneGuid.ToString());
                if (listItem != null)
                {
                    ddZoneGuid.ClearSelection();
                    listItem.Selected = true;
                }
            }

            txtPostalCode.Text = store.PostalCode;
            txtPhone.Text = store.Phone;
            txtFax.Text = store.Fax;
            txtSalesEmail.Text = store.SalesEmail;
            txtSupportEmail.Text = store.SupportEmail;
            txtEmailFrom.Text = store.EmailFrom;
            txtOrderBCCEmail.Text = store.OrderBccEmail;


            chkIsClosed.Checked = store.IsClosed;
            edClosedMessage.Text = store.ClosedMessage;



        }

        private void BindDropdownLists()
        {
            BindCountryList();
            BindZoneList();

        }

        private void BindCountryList()
        {
            DataTable dataTable = GeoCountry.GetList();
            ddCountryGuid.DataSource = dataTable;
            ddCountryGuid.DataBind();
            if (ddCountryGuid.Items.FindByValue("99f791e7-7343-42e8-8c19-3c41068b5f8d") != null)
            {
                ddCountryGuid.Items.FindByValue("99f791e7-7343-42e8-8c19-3c41068b5f8d").Selected = true;
            }
        }

        private void ddCountryGuid_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindZoneList();
        }

        private void BindZoneList()
        {
            if (ddCountryGuid.SelectedIndex <= -1) return;
            Guid countryGuid = new Guid(ddCountryGuid.SelectedValue);
            using (IDataReader reader = GeoZone.GetByCountry(countryGuid))
            {
                ddZoneGuid.DataSource = reader;
                ddZoneGuid.DataBind();
            }
        }




        private void btnSave_Click(object sender, EventArgs e)
        {
            Page.Validate("estore");
            if ((!Page.IsValid) || (store == null)) return;
            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();

            if (store.SiteGuid == Guid.Empty)
            {
                store.SiteGuid = siteSettings.SiteGuid;
            }
            if (store.ModuleId == -1)
            {
                store.ModuleId = moduleId;
            }

            Module module1 = new Module(moduleId) {ModuleTitle = txtName.Text};
            module1.Save();

            store.Name = txtName.Text;
            store.Description = edDescription.Text;
            store.OwnerName = txtOwnerName.Text;
            store.OwnerEmail = txtOwnerEmail.Text;
            store.SalesEmail = txtSalesEmail.Text;
            store.SupportEmail = txtSupportEmail.Text;
            store.EmailFrom = txtEmailFrom.Text;
            store.OrderBccEmail = txtOrderBCCEmail.Text;
            store.Phone = txtPhone.Text;
            store.Fax = txtFax.Text;
            store.Address = txtAddress.Text;
            store.City = txtCity.Text;

            if (!String.IsNullOrEmpty(ddZoneGuid.SelectedValue))
            {
                store.ZoneGuid = new Guid(ddZoneGuid.SelectedValue);
            }

            store.PostalCode = txtPostalCode.Text;

            if (!String.IsNullOrEmpty(ddCountryGuid.SelectedValue))
            {
                store.CountryGuid = new Guid(ddCountryGuid.SelectedValue);
            }

            store.IsClosed = chkIsClosed.Checked;
            store.ClosedMessage = edClosedMessage.Text;


            if (store.Guid == Guid.Empty)
            {
                store.Created = DateTime.UtcNow;
                store.CreatedBy = siteUser.UserGuid;

            }

            store.Save();

            List<TaxClass> taxClasses = TaxClass.GetList(siteSettings.SiteGuid);

            if (taxClasses.Count == 0)
            {
                TaxClass taxClass = new TaxClass
                                        {
                                            SiteGuid = siteSettings.SiteGuid,
                                            Title = eStoreResources.TaxClassTaxable,
                                            Description = eStoreResources.TaxClassTaxable
                                        };
                taxClass.Save();

                taxClass = new TaxClass
                               {
                                   SiteGuid = siteSettings.SiteGuid,
                                   Title = eStoreResources.TaxClassNotTaxable,
                                   Description = eStoreResources.TaxClassNotTaxable
                               };
                taxClass.Save();


            }

            WebUtils.SetupRedirect(this, Request.RawUrl);
        }


        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.StoreSettingsLink);

            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.StoreSettingsLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            ltrTitle.Text = eStoreResources.StoreSettingsLink;
            btnSave.Text = eStoreResources.StoreSettingsSaveButton;

            litSettingsTab.Text = eStoreResources.StoreContactInfoTab;
            litDescriptionTab.Text = eStoreResources.StoreDescriptionTab;
            litClosedTab.Text = eStoreResources.StoreOpenClosedTab;

            edDescription.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            edDescription.WebEditor.Height = Unit.Parse("220px");

            edClosedMessage.WebEditor.ToolBar = ToolBar.FullWithTemplates;
            edClosedMessage.WebEditor.Height = Unit.Parse("220px");

        }

        private void LoadSettings()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", -1);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", -1);

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }

            if ((moduleId > -1) && (store.ModuleId == moduleId))
            {
                module = new Module(moduleId);

            }
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadSideContent(false, false, true, true, 0);
            base.OnInit(e);
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            ddCountryGuid.SelectedIndexChanged += ddCountryGuid_SelectedIndexChanged;
            SuppressPageMenu();
            SuppressGoogleAds();
            SiteUtils.SetupEditor(edDescription);
            SiteUtils.SetupEditor(edClosedMessage);
        }
        #endregion
    }
}
